package main

import (
	"crypto/tls"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"time"
)

// todo 参考: https://studygolang.com/articles/4489
// golang中发送http请求的几种常见情况

// 基础场景
func base() {
	client := &http.Client{}

	url := "http://www.baidu.com"
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		panic(err)
	}
	resp, _ := client.Do(req)

	_, err = io.Copy(os.Stdout, resp.Body)
	if err != nil {
		panic(err)
	}
	//返回的状态码
	status := resp.StatusCode

	fmt.Println(status)
}

// client.Get/Post
func baseGet() {
	client := &http.Client{}

	url := "http://www.baidu.com"
	resp, err := client.Get(url)
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(os.Stdout, resp.Body)
	if err != nil {
		panic(err)
	}
	//返回的状态码
	status := resp.StatusCode

	fmt.Println(status)
}

// http.Get/Post
func httpGet() {
	url := "http://www.baidu.com"
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(os.Stdout, resp.Body)
	if err != nil {
		panic(err)
	}
	//返回的状态码
	status := resp.StatusCode

	fmt.Println(status)
}

// 配置 client
// client 默认配置:
//Transport RoundTripper  默认: http.DefaultTransport
//CheckRedirect func(req *Request, via []*Request) error
//Jar CookieJar
//Timeout time.Duration
func custHTTP() {
	tr := &http.Transport{
		Dial: (&net.Dialer{
			Timeout: 10 * time.Second,
		}).Dial,
		MaxIdleConns:    4,
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	// Create client
	client := &http.Client{Transport: tr, Timeout: time.Second * 5}

	req, err := http.NewRequest("GET", "https://www.baidu.com/", nil)
	if err != nil {
		panic(err)
	}
	// Add Headers
	req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")

	resp, _ := client.Do(req)
	// 1
	//respBody, err := ioutil.ReadAll(resp.Body)
	//defer resp.Body.Close()
	//fmt.Println(string(respBody))
	// 2
	_, err = io.Copy(os.Stdout, resp.Body)
	if err != nil {
		panic(err)
	}
	//返回的状态码
	status := resp.StatusCode

	fmt.Println(status)
}

func main() {
	// 基础场景
	// base()
	custHTTP()
}
